﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/


using System.IO;
using Tesla.Content;
using Tesla.Graphics;
using D3DC = SlimDX.D3DCompiler;

namespace Tesla.Direct3D10.Content.Loaders {
    /// <summary>
    /// Resource loader that compiles Direct3D10 Shader Model 4.0 FX files.
    /// </summary>
    public sealed class D3D10EffectLoader : ResourceLoader<Effect> {

        /// <summary>
        /// Creates a new D3D10EffectLoader
        /// </summary>
        public D3D10EffectLoader() : base(".fx") { }

        /// <summary>
        /// Loads an Effect from the resource.
        /// </summary>
        /// <param name="resource">Resource that references the FX file</param>
        /// <param name="parameters">Loader parameters</param>
        /// <returns>Compiled effect</returns>
        public override Effect Load(IResource resource, LoaderParameters parameters) {
            EffectInclude include = new EffectInclude(ContentManager, Path.GetDirectoryName(resource.FullName));
            D3DC.ShaderBytecode byteCode = D3DC.ShaderBytecode.CompileFromFile(resource.FullName, "fx_4_0", D3DC.ShaderFlags.None, D3DC.EffectFlags.None, null, include);
            byte[] bytes = new byte[byteCode.Data.Length];
            System.IntPtr ptr = Tesla.Util.MemoryHelper.PinObject(bytes);
            Tesla.Util.MemoryHelper.Copy(byteCode.Data.DataPointer, ptr, bytes.Length);
            Tesla.Util.MemoryHelper.UnpinObject(bytes);
            byteCode.Dispose();

            Effect e = new Effect(bytes);
            e.Name = resource.Name;

            return e;
        }

    }
}
